package com.tbit.uqbike.webmanager.controller.interceptor.stat;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by MyWin on 2017/5/12.
 */
public class StatInterceptor implements HandlerInterceptor {

    private StatServices statServices;
    private String comName;
    private boolean open = false;

    public boolean isOpen() {
        return open;
    }

    public void setOpen(boolean open) {
        this.open = open;
    }

    public String getComName() {
        return comName;
    }

    public void setComName(String comName) {
        this.comName = comName;
    }

    public StatServices getStatServices() {
        return statServices;
    }

    public void setStatServices(StatServices statServices) {
        this.statServices = statServices;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        httpServletRequest.setAttribute("st", System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        Long l = (Long) httpServletRequest.getAttribute("st");
        if (null != statServices && l != null && open) {
            statServices.recordStatData(comName, httpServletRequest.getRequestURI(),
                    Long.toString(System.currentTimeMillis() - l), new Date(l), "");
        }
        //
    }
}
